package com.veo.controller;

import com.github.pagehelper.PageInfo;
import com.veo.domain.Permission;
import com.veo.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/permissionController")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/findAllPermission")
    public ModelAndView findAllPermission(@RequestParam(value = "page",defaultValue = "1",required = false)Integer page, @RequestParam(value = "size",defaultValue = "5",required = false)Integer size, @RequestParam(value = "searcherName",defaultValue = "",required = false)String searcherName) throws UnsupportedEncodingException {
        ModelAndView mv=new ModelAndView();
        //判断是乱码 (GBK包含全部中文字符；UTF-8则包含全世界所有国家需要用到的字符。)
        if (!(Charset.forName("GBK").newEncoder().canEncode(searcherName))) {
            //转码UTF8
            searcherName = new String(searcherName.getBytes("ISO-8859-1"), "utf-8");
        }
        List<Permission> allPermission = permissionService.findAllPermission(page,size,searcherName);
        //保存分页信息
        PageInfo permissionList=new PageInfo(allPermission);
        mv.addObject("permissionList",permissionList);
        mv.addObject("searcherName",searcherName);
        mv.setViewName("permission-list");
        return mv;
    }

    @RequestMapping("/addPermission")
    public String addPermission(Permission permission){
        String id= UUID.randomUUID().toString().replace("-","").toUpperCase();
        permission.setId(id);
        int count = permissionService.addPermission(permission);
        return "redirect:findAllPermission";
    }

    @RequestMapping("/deletePermissionByIds")
    public String deletePermissionByIds(String idStr){
        if (idStr!=null && idStr.length()>0&& idStr!=""){
            String[] ids = idStr.split(",");
            for (String id : ids) {
                permissionService.deleteRolePermissionId(id);
                permissionService.deletePermissionById(id);
            }
        }
        return "redirect:findAllPermission";
    }

}
